package com.maint.m

import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log

import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.lifecycle.lifecycleScope
// AppDataManager可能不存在，移除导入
import com.rokid.security.phone.sdk.api.PSecuritySDK
import com.rokid.security.phone.sdk.api.wifip2p.listener.IWifiP2PClientListener
import android.net.wifi.p2p.WifiP2pDevice
import kotlinx.coroutines.launch
import com.maint.m.data.GlobalData

class GlassConnectionActivity : AppCompatActivity() {

    private lateinit var searchBtn: Button
    private lateinit var devicesListView: ListView
    private lateinit var statusTextView: TextView
    private lateinit var deviceAdapter: ArrayAdapter<String>
    private val foundDevices = mutableListOf<WifiP2PDeviceInfo>()
    private val deviceNames = mutableListOf<String>()
    private var connectionStatus = false
    private val TAG = "GlassConnectionActivity::"
    
    // WiFi P2P所需权限
    private val REQUIRED_PERMISSIONS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        arrayOf(
            android.Manifest.permission.NEARBY_WIFI_DEVICES,
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.CHANGE_WIFI_STATE,
            android.Manifest.permission.ACCESS_WIFI_STATE
        )
    } else {
        arrayOf(
            android.Manifest.permission.ACCESS_FINE_LOCATION,
            android.Manifest.permission.CHANGE_WIFI_STATE,
            android.Manifest.permission.ACCESS_WIFI_STATE
        )
    }
    private val PERMISSION_REQUEST_CODE = 1001
    
    // WifiP2P设备信息类
    data class WifiP2PDeviceInfo(val deviceName: String, val deviceAddress: String, val device: Any?)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_glass_connection)

        // 初始化移动引擎
        initMobileEngine()
        
        // 初始化视图
        initViews()
        
        // 设置WifiP2P连接状态监听
        setupWifiP2PListener()
        
        // 设置搜索按钮点击事件
        setupButtonListeners()
    }

    private fun initViews() {
        searchBtn = findViewById(R.id.searchBtn)
        devicesListView = findViewById(R.id.devicesListView)
        statusTextView = findViewById(R.id.statusTextView)

        // 初始化设备列表适配器
        deviceAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, deviceNames)
        devicesListView.adapter = deviceAdapter
        
        // 设置设备列表点击事件
        devicesListView.setOnItemClickListener { _, _, position, _ ->
            if (position < foundDevices.size) {
                val device = foundDevices[position]
                connectToDevice(device)
            }
        }
    }
    
    // 检查权限是否已授予
    private fun checkPermissions(): Boolean {
        for (permission in REQUIRED_PERMISSIONS) {
            if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "缺少权限: $permission")
                return false
            }
        }
        return true
    }
    
    // 请求权限
    private fun requestPermissions() {
        Log.d(TAG, "请求WiFi P2P相关权限")
        ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE)
    }
    
    // 处理权限请求结果
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                Log.d(TAG, "所有权限已授予，可以开始扫描")
                Toast.makeText(this, "权限已授予，可以开始扫描设备", Toast.LENGTH_SHORT).show()
            } else {
                Log.e(TAG, "权限被拒绝，无法使用WiFi P2P功能")
                Toast.makeText(this, "权限被拒绝，无法使用WiFi P2P功能", Toast.LENGTH_SHORT).show()
                
                // 列出被拒绝的权限
                for (i in permissions.indices) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        Log.e(TAG, "被拒绝的权限: ${permissions[i]}")
                    }
                }
            }
        }
    }
    
    private fun setupButtonListeners() {
        searchBtn.setOnClickListener {
            // 点击扫描前再次检查权限
            if (checkPermissions()) {
                startWifiP2PScan()
            } else {
                requestPermissions()
                Toast.makeText(this, "请先授予必要的权限", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun startWifiP2PScan() {
        try {
            // 检查是否已连接P2P，如果已连接则不执行扫描
            if (connectionStatus) {
                Log.e(TAG, "已连接P2P，停止扫描")
                runOnUiThread {
                    statusTextView.text = "已连接P2P，停止扫描"
                    statusTextView.setTextColor(getColor(android.R.color.holo_green_dark))
                }
                return
            }
            
            // 再次检查权限
            if (!checkPermissions()) {
                Log.e(TAG, "缺少必要权限，无法开始扫描")
                runOnUiThread {
                    statusTextView.text = "缺少必要权限，无法扫描"
                    statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                }
                return
            }
            
            Log.e(TAG, "开始扫描流程")
            // 清空之前的设备列表
            foundDevices.clear()
            deviceNames.clear()
            deviceAdapter.notifyDataSetChanged()
            
            statusTextView.text = "正在扫描WifiP2P设备..."
            statusTextView.setTextColor(getColor(android.R.color.holo_blue_dark))
            Log.e(TAG, "UI状态更新完成")
            
            // 使用SDK开始WifiP2P扫描
            val wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
            Log.e(TAG, "获取WifiP2P服务: ${wifiP2PClientService != null}")
            
            if (wifiP2PClientService != null) {
                Log.e(TAG, "准备开始WifiP2P扫描")
                // 先尝试获取已连接的设备
                try {
                    // 尝试调用可能存在的方法获取设备列表
                    val hasGetPeersMethod = wifiP2PClientService.javaClass.methods.any { it.name == "getPeers" }
                    Log.e(TAG, "是否有getPeers方法: $hasGetPeersMethod")
                } catch (e: Exception) {
                    Log.e(TAG, "检查方法异常: ${e.message}")
                }
                
                wifiP2PClientService.startDiscoverPeers { result ->
                        Log.e(TAG, "扫描完成回调结果: $result, isSuccess: ${result.isSuccess}")
                        
                        // 扫描完成后更新UI状态
                        runOnUiThread {
                            if (!result.isSuccess) {
                                statusTextView.text = "扫描失败: 未知错误"
                                statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                            }
                        }
                    }
                
                // 设置超时处理
                lifecycleScope.launch { 
                    kotlinx.coroutines.delay(10000) // 10秒超时
                    runOnUiThread {
                        if (statusTextView.text.contains("正在扫描")) {
                            Log.e(TAG, "扫描超时")
                            statusTextView.text = "扫描超时，请重试"
                            statusTextView.setTextColor(getColor(android.R.color.holo_orange_light))
                        }
                    }
                }
            } else {
                Log.e(TAG, "WifiP2P服务初始化失败")
                statusTextView.text = "WifiP2P服务初始化失败"
                statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                Toast.makeText(this, "WifiP2P服务初始化失败", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "WifiP2P扫描异常", e)
            statusTextView.text = "扫描失败: ${e.message}"
            statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
            Toast.makeText(this, "扫描失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    // WifiP2P连接
    private fun connectToDevice(device: WifiP2PDeviceInfo) {
        val deviceName = device.deviceName
        // 移除AppDataManager引用
        Log.e(TAG, "连接设备: $deviceName, 地址: ${device.deviceAddress}")
        
        try {
            val wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
            if (wifiP2PClientService != null) {
                statusTextView.text = "正在连接 $deviceName..."
                statusTextView.setTextColor(getColor(android.R.color.holo_blue_dark))
                
                // 创建WifiP2pDevice对象
                val wifiP2pDevice = WifiP2pDevice()
                wifiP2pDevice.deviceAddress = device.deviceAddress
                wifiP2pDevice.deviceName = device.deviceName
                
                wifiP2PClientService.connectDevice(wifiP2pDevice) { result ->
                    Log.e(TAG, "连接结果: ${result.isSuccess}, 结果详情: $result")
                    runOnUiThread {
                        if (result.isSuccess) {
                            connectionStatus = true
                            // 使用本地变量记录连接状态
                            statusTextView.text = "连接成功: $deviceName"
                            statusTextView.setTextColor(getColor(android.R.color.holo_green_dark))
                            Log.e(TAG, "设备连接成功: $deviceName, 地址: ${device.deviceAddress}")
                            Toast.makeText(this@GlassConnectionActivity, "连接成功: $deviceName", Toast.LENGTH_SHORT).show()

                            // 连接成功后停止扫描
                            stopWifiP2PScan()

                            PSecuritySDK.getMessageService()?.sendTextMessageByP2P("连接成功")

                            // 设置全局P2P连接状态为已连接，确保TicketListActivity能正确识别连接状态
                            GlobalData.setP2pConnectState(true)
                            Log.e(TAG, "已设置全局P2P连接状态为true")
                            
                            // 根据GlobalData.isGlassConnect()的实现，还需要设置btConnectState为true
                            // 因为isGlassConnect()需要同时检查p2pConnectState和btConnectState是否都为true
                            GlobalData.setBtConnectState(true)
                            Log.e(TAG, "已设置全局蓝牙连接状态为true")
                            
                            // 延迟1500毫秒后再关闭页面，给用户时间看到成功提示
                            Thread {
                                Thread.sleep(1500)
                                runOnUiThread {
                                    Log.e(TAG, "延迟后关闭连接页面")
                                    // 设置结果代码表示连接成功，这样调用方可以知道连接状态
                                    setResult(RESULT_OK)
                                    finish() // 关闭当前页面并返回上一页
                                }
                            }.start()
                        } else {
                            connectionStatus = false
                            // 使用本地变量记录连接状态
                            statusTextView.text = "连接失败"
                            statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                            Log.e(TAG, "设备连接失败: $deviceName, 原因: ${result.javaClass.simpleName}")
                            Toast.makeText(this@GlassConnectionActivity, "连接失败: $deviceName", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            } else {
                Log.e(TAG, "WifiP2P服务不可用")
                Toast.makeText(this, "WifiP2P服务不可用", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "连接异常", e)
            Toast.makeText(this, "连接异常: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    // 过滤WifiP2P设备名称
    private fun wifiDeviceFilter(deviceName: String?): Boolean {
        if (deviceName.isNullOrEmpty() || "null".equals(deviceName.lowercase())) {
            return false
        }
        
        // 正式版本只展示Glass3开头的设备
        if (deviceName.startsWith("Glass3")) {
            return true
        }
        return false
    }
    
    private fun setupWifiP2PListener() {
        try {
            val wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
            if (wifiP2PClientService != null) {
                // 设置WifiP2P客户端监听器
                wifiP2PClientService.addWifiP2PClientListener(object : IWifiP2PClientListener {
                    override fun onPeersAvailable(devices: List<WifiP2pDevice>) {
                        // 清空现有列表
                        foundDevices.clear()
                        deviceNames.clear()
                        
                        // 使用Log.e打印所有扫描到的设备信息
                        Log.e(TAG, "扫描到设备总数: ${devices.size}")
                        
                        // 过滤并添加符合条件的设备
                        devices.forEachIndexed { index, device ->
                            val deviceName = device.deviceName
                            val deviceAddress = device.deviceAddress
                            val deviceStatus = when(device.status) {
                                WifiP2pDevice.AVAILABLE -> "AVAILABLE"
                                WifiP2pDevice.INVITED -> "INVITED"
                                WifiP2pDevice.CONNECTED -> "CONNECTED"
                                WifiP2pDevice.FAILED -> "FAILED"
                                WifiP2pDevice.UNAVAILABLE -> "UNAVAILABLE"
                                else -> "UNKNOWN"
                            }

                            Log.i(TAG, "设备$index - 名称: $deviceName, 地址: $deviceAddress")

                            if (deviceName != null && wifiDeviceFilter(deviceName)) {
                                foundDevices.add(WifiP2PDeviceInfo(deviceName, device.deviceAddress, device))
                                deviceNames.add(deviceName)
                                Log.e(TAG, "符合条件的设备: $deviceName")
                            } else {
                                Log.e(TAG, "不符合条件的设备: $deviceName")
                            }
                        }
                        
                        // 更新UI
                        runOnUiThread {
                            deviceAdapter.notifyDataSetChanged()
                            statusTextView.text = "发现 ${foundDevices.size} 个设备"
                            statusTextView.setTextColor(getColor(android.R.color.holo_blue_dark))
                            Log.e(TAG, "最终显示在列表的设备数量: ${foundDevices.size}")
                        }
                    }

                    override fun onWifiP2pEnabled(enabled: Boolean) {
                        Log.d(TAG, "WifiP2P 状态变化: $enabled")
                        runOnUiThread {
                            if (enabled) {
                                connectionStatus = true
                                // 使用本地变量记录连接状态
                                statusTextView.text = "已连接"
                                statusTextView.setTextColor(getColor(android.R.color.holo_green_dark))
                            } else {
                                connectionStatus = false
                                // 使用本地变量记录连接状态
                                statusTextView.text = "未连接"
                                statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                            }
                        }
                    }

                    override fun onSelfDeviceAvailable(device: WifiP2pDevice) {
                        Log.d(TAG, "自身设备可用: ${device.deviceName}")
                    }
                })
            }
        } catch (e: Exception) {
            Log.e(TAG, "设置WifiP2P监听器失败", e)
            Toast.makeText(this, "设置WifiP2P监听器失败", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun disconnectWifiP2P() {
        try {
            val wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
            if (wifiP2PClientService != null) {
                wifiP2PClientService.disconnect()
                connectionStatus = false
                // 使用本地变量记录连接状态
                statusTextView.text = "已断开连接"
                statusTextView.setTextColor(getColor(android.R.color.holo_blue_dark))
                Toast.makeText(this, "已断开连接", Toast.LENGTH_SHORT).show()
            }
        } catch (e: Exception) {
            Log.e(TAG, "断开WifiP2P连接异常", e)
            Toast.makeText(this, "断开连接异常: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    private fun checkConnectionStatus() {
        try {
            val wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
            if (wifiP2PClientService != null) {
                // 直接根据本地connectionStatus变量显示当前连接状态
                runOnUiThread {
                    if (connectionStatus) {
                        statusTextView.text = "当前连接状态: 已连接"
                        statusTextView.setTextColor(getColor(android.R.color.holo_green_dark))
                    } else {
                        statusTextView.text = "当前连接状态: 未连接"
                        statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                    }
                }
                
                // 只有在未连接状态下才启动扫描
                if (!connectionStatus) {
                    wifiP2PClientService.startDiscoverPeers { result ->
                        Log.d(TAG, "状态检查时扫描结果: $result")
                        // 扫描完成后更新状态显示
                        runOnUiThread {
                            if (!connectionStatus) {
                                statusTextView.text = "当前连接状态: 未连接"
                                statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "检查连接状态异常", e)
            runOnUiThread {
                statusTextView.text = "当前连接状态: 检查失败"
                statusTextView.setTextColor(getColor(android.R.color.holo_red_dark))
            }
        }
    }
    
    /**
     * 停止WifiP2P扫描
     */
    private fun stopWifiP2PScan() {
        try {
            val wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
            if (wifiP2PClientService != null) {
                // 尝试使用反射调用停止扫描的方法
                try {
                    val stopScanMethod = wifiP2PClientService.javaClass.getMethod("stopPeerDiscovery")
                    stopScanMethod.invoke(wifiP2PClientService)
                    Log.e(TAG, "停止WifiP2P扫描成功")
                } catch (e: NoSuchMethodException) {
                    Log.w(TAG, "停止扫描方法不可用，忽略")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "停止WifiP2P扫描异常", e)
        }
    }

    private fun initMobileEngine() {
        try {
            Log.d(TAG, "开始初始化移动引擎")
            Log.d(TAG, "当前Android版本: ${Build.VERSION.RELEASE}, API级别: ${Build.VERSION.SDK_INT}")
            
            // 针对Android 8.0 (API 26) 的特殊处理
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
                Log.d(TAG, "Android 8.0设备，尝试兼容性处理")
                // 在Android 8上，可能需要先确保WiFi已启用
                val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as android.net.wifi.WifiManager
                if (!wifiManager.isWifiEnabled) {
                    Log.d(TAG, "Android 8.0: WiFi未启用，尝试启用")
                    // 注意：在Android 10及以上，这个方法已弃用，但在Android 8上仍然可用
                    wifiManager.isWifiEnabled = true
                    Log.d(TAG, "Android 8.0: WiFi已尝试启用")
                }
                
                // 给Android 8设备一些额外的初始化时间
                Thread.sleep(1000)
            }
            
            // 尝试多次获取WifiP2P服务，解决Android 8上的初始化问题
            var retryCount = 0
            val maxRetries = 3
            var wifiP2PClientService: Any? = null
            
            while (retryCount < maxRetries && wifiP2PClientService == null) {
                retryCount++
                Log.d(TAG, "尝试获取WifiP2P服务 (第${retryCount}次)")
                wifiP2PClientService = PSecuritySDK.getWifiP2PClientService()
                
                if (wifiP2PClientService == null) {
                    Log.d(TAG, "WifiP2P服务暂时不可用，${retryCount}秒后重试")
                    Thread.sleep(retryCount * 1000L) // 递增的延迟时间
                }
            }
            
            if (wifiP2PClientService != null) {
                Log.d(TAG, "WifiP2P服务可用")
                // 验证服务的关键方法是否可用
                val hasStartDiscoverMethod = try {
                    wifiP2PClientService.javaClass.getDeclaredMethod("startDiscoverPeers", Function1::class.java)
                    true
                } catch (e: NoSuchMethodException) {
                    false
                }
                Log.d(TAG, "WifiP2P服务包含startDiscoverPeers方法: $hasStartDiscoverMethod")
            } else {
                Log.e(TAG, "WifiP2P服务不可用，已尝试${maxRetries}次")
                val errorMessage = if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O) {
                    "Android 8.0设备WiFi P2P服务初始化失败，请确保WiFi已开启"
                } else {
                    "WifiP2P服务初始化失败"
                }
                Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show()
            }
            
            Log.d(TAG, "移动引擎初始化完成")
        } catch (e: Exception) {
            Log.e(TAG, "移动引擎初始化异常", e)
            Toast.makeText(this, "移动引擎初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 检查连接状态
        checkConnectionStatus()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        try {
            // 清理资源
            // 移除监听器代码
        } catch (e: Exception) {
            Log.e(TAG, "清理WifiP2P资源失败: ${e.message}")
        }
    }
}